﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using FinanSoft.BusinessLayer;
using FinanSoft.Utilities;

namespace FinanSoft.PresentacionFacturasExternas
{
    public partial class frmFacturaExterna : Form
    {
        private bool _Checked;

        public frmFacturaExterna()
        {
            InitializeComponent();
            _Checked = false;
        }

        /// <summary>
        /// Evento para cargar un archivo guardado
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCargar_Click(object sender, EventArgs e)
        {
            String fileName;

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = Constants.FILE_FILTER_XML;
            dialog.Title = Constants.FILE_DIALOG_TITLE;

            if (dialog.ShowDialog() == DialogResult.OK && dialog.FileName != "")
            {
                fileName = dialog.FileName;
                txtFile.Text = fileName;
            }
        }

        /// <summary>
        /// Evento para cerrar la ventana
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCerrar_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Evento para cuando se va a probar o guardar la factura externa
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAceptar_Click(object sender, EventArgs e)
        {
            String fileName = txtFile.Text;
            String logFileName = txtLogFileName.Text;
            // Aqui llamo al método que me evalúa el archivo
            CheckFiles(fileName, logFileName);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String logFileName;

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = Constants.FILE_FILTER_TXT;
            dialog.Title = Constants.FILE_DIALOG_TITLE2;
            dialog.AddExtension = true;
            dialog.DefaultExt = Constants.DEFAULT_EXTENSION_TXT;
            dialog.CheckFileExists = false;

            if (dialog.ShowDialog() == DialogResult.OK && dialog.FileName != "")
            {
                logFileName = dialog.FileName;
                txtLogFileName.Text = logFileName;
            }
        }

        /// <summary>
        /// Se encarga de revisar los archivos, y si está en modo definitivo se guarda en la base de datos
        /// </summary>
        /// <param name="fileName">Nombre del archivo donde se encuentra almacenada la factura</param>
        /// <param name="logFileName">Nombre de la bitácora en donde se escriben los resultados</param>
        private void CheckFiles(String fileName, String logFileName)
        {
            XmlDocument xmlDoc = new XmlDocument();
            List<int> documentIds = new List<int>();
            try
            {
                if (!_Checked)
                {
                    xmlDoc.Load(fileName);
                    XmlNodeList list = xmlDoc.GetElementsByTagName(Constants.TAG_NODE_NAME_DOCUMENT);
                    foreach (XmlNode node in list)
                    {
                        int id = ExternInvoiceManager.GetInstance().CheckInvoiceFile(node, logFileName);
                        if (id != Constants.INVALID_ID)
                            documentIds.Add(id);
                    }
                    _Checked = true;
                }

                if (radioDef.Checked)
                    foreach (int id in documentIds)
                        ExternInvoiceManager.GetInstance().SaveExternInvoice(id, logFileName);
                
                MessageBox.Show(MessageConstants.CHECK_OPERATION_FINISHED, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                Close();
            }
            catch (XmlException ex)
            {
                MessageBox.Show(MessageConstants.CHECK_OPERATION_FAILED, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
